package com.chenwei.rabbit;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author: chenwei
 * @date: 2021/3/31 14:17
 */
public class MQUtils {

    private static ConnectionFactory connectionFactory;
    static {
        //可一次创建重复使用的重量资源
        connectionFactory = new ConnectionFactory();
        connectionFactory.setPort(5672);
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setVirtualHost("/study");
        connectionFactory.setUsername("chenwei");
        connectionFactory.setPassword("chenwei");
    }

//    public static Connection getConnection(){
//        try {
//            //创建mq的连接工厂
//            ConnectionFactory connectionFactory = new ConnectionFactory();
//            //设置连接的mq主机
//            //设置端口号
//            connectionFactory.setPort(5672);
//            connectionFactory.setHost("127.0.0.1");
//            //设置连接的虚拟主机
//            connectionFactory.setVirtualHost("/study");
//            //设置用户信息
//            connectionFactory.setUsername("chenwei");
//            connectionFactory.setPassword("chenwei");
//            //获取连接对象
//             return connectionFactory.newConnection();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (TimeoutException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    //上面方法得改进--将重复代码放到静态代码块
    public static Connection getConnection(){
        try {
            return connectionFactory.newConnection();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        return null;
    }

    //关闭通道和连接
    public static void close(Channel channel,Connection connection){
        try {
            if (channel!=null)channel.close();
            if (connection!=null)connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
